<template>
    <el-upload multiple
               action="/a/upload/local"
               :accept="accept"
               :limit="limit"
               :on-remove="remove"
               :on-exceed="limitError"
               :before-upload="beforeUpload"
               :on-success="success"
               :file-list="uploaded">
        <el-button type="primary" icon="el-icon-upload">点击上传</el-button>
    </el-upload>
</template>

<script>
    import {Upload} from "element-ui";

    export default {
        components: {elUpload: Upload},
        props: {
            files: {
                type: Array,
                default() {
                    return [];
                }
            },
            accept: {
                type: String,
                default: '.pdf'
            },
            limit: {
                type: Number,
                default: 1,
            },
            size: {
                type: Number,
                default: 2,
            },
        },
        model: {
            prop: 'files'
        },
        computed: {
            uploaded() {
                let files = [];
                this.files.forEach(file => {
                    files.push({
                        name: file.name,
                        url: file.url
                    })
                })
                return files;
            }
        },
        methods: {
            // 上传成功
            success(res, file, fileList) {
                if (res.code == 1) {
                    this.update(fileList);
                } else {
                    this.$message.warning(res.msg);
                }
            },
            // 删除
            remove(file, fileList) {
                this.update(fileList);
            },
            //文件超出限制
            limitError() {
                this.$message.warning('最多只能上传10个pdf文件');
            },
            // 文件上传前
            beforeUpload(file) {
                // 判断文件体积
                if (file.size > this.size * 1048576) {
                    this.$message.warning(`文件不能超过 ${this.size}M`);
                    return false;
                }
                //使用oss上传时用到，判断上传token是否失效
            },
            // 更新文件列表回传
            update(files) {
                let images = [];
                files.forEach(img => {
                    if (!img.response) {
                        images.push({
                            name: img.name,
                            url: img.url,
                        })
                    } else if (img.status == 'success' && img.response.code == 1) {
                        images.push({
                            name: img.response.data.name,
                            url: img.response.data.url,
                        })
                    }
                })
                this.$emit('input', images);
            }
        }
    }
</script>
